/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package nnet2.learning;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;

import nnet2.gui.OnLineLearningPlotPanel;
import nnet2.net.RecursiveMultiLayerPerceptron;

/**
 *
 * @author kalinskia
 */
public class FileLearning {
    private final String dataFile;
    private ArrayList<Double> data;
    private ArrayList<Double> forecast = new ArrayList<Double>();
    private ArrayList<Double> error = new ArrayList<Double>();
    private final RecursiveMultiLayerPerceptron rmlp;

    public FileLearning(RecursiveMultiLayerPerceptron rmlp,String fileName){
        this.rmlp = rmlp;
        this.dataFile = fileName;
        this.data = new ArrayList<Double>();
        loadStackData();
    }

    public void traindAndLearn(boolean visual){
        double err, out;
        OnLineLearningPlotPanel panel = null;
        if(visual)
            panel = OnLineLearningPlotPanel.showPlot();
        System.out.println("Expected;Predicted;Error");
        for(int i = 0; i < data.size()-1;i++){
            err = rmlp.nextTeachingSample(data.get(i), data.get(i + 1));
            error.add(err);
            out = rmlp.getCurrentForecast();
            forecast.add(out);
            System.out.format("%f;%f;%f\n",data.get(i+1),out, Math.abs(err));
            if(visual){
                panel.nextPrediction(data.get(i+1), out, err);
                panel.setMse(rmlp.getMSE(10));
            }
        }
    }
    
    public void traindAndLearnSilent(boolean visual){
        double err, out;
        for(int i = 0; i < data.size()-1;i++){
            err = rmlp.nextTeachingSample(data.get(i), data.get(i + 1));
            error.add(err);
            out = rmlp.getCurrentForecast();
            forecast.add(out);
            //System.out.format("%f;%f;%f\n",data.get(i+1),out, Math.abs(err));
        }
    }

    private boolean loadStackData() {
        FileReader r;
        BufferedReader buf;
        String line;
        ArrayList<Double> data = new ArrayList<Double>();
        try {
            r = new FileReader(dataFile);
            buf = new BufferedReader(r);

            while ((line = buf.readLine()) != null) {
                try {
                    double d = Double.parseDouble(line);
                    data.add((double)d);
                } catch (NumberFormatException ne) {
                    System.out.format("Line %s was not recognised as double", line);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        this.data = data;
        return true;
    }
}
